package com.langyue.recordmanage.utils;

import org.springframework.util.DigestUtils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @Description: MD5加密工具
 * @Author: wanglang
 * @CreateTime: 2022/4/1
 * @Company:
 */
public class MD5Util {
    /**
     * MD5加码 生成32位md5码
     * @param inStr
     * @return
     */
    public static String string2MD5(String inStr){
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        char[] charArray = inStr.toCharArray();
        byte[] byteArray = new byte[charArray.length];

        for (int i = 0; i < charArray.length; i++) {
            byteArray[i] = (byte) charArray[i];
        }
        byte[] md5Bytes = md5.digest(byteArray);

        StringBuilder hexValue = new StringBuilder();

        for (int i = 0; i < md5Bytes.length; i++) {
            int val = ((int) md5Bytes[i]) & 0xff;
            if (val < 16){
                hexValue.append("0");
            }
            hexValue.append(Integer.toHexString(val));
        }
        return hexValue.toString();
    }

    /**
     * 加密解密算法 执行一次加密，两次解密
     * @param inStr
     * @return
     */
    public static String convertMD5(String inStr){
        char[] a = inStr.toCharArray();
        for (int i = 0; i < a.length; i++) {
            a[i] = (char)(a[i] ^ 't');
        }
        String s = new String(a);
        return s;
    }

    /**
     * spring自带的 MD5 加密
     * @param inStr
     * @return
     */
    public static String springMD5(String inStr){
        String md5 = DigestUtils.md5DigestAsHex(inStr.getBytes());
        return md5;
    }

    public static String getMD5(String inStr){
        /**
         * 原密码加密一次
         * 获取原密码加密后的前8位字符
         * 8位字符+加密后的字符串     再加密一次
         */
        String md501 = DigestUtils.md5DigestAsHex(inStr.getBytes());
        String temp = md501.substring(0, 8);
        String md502 = DigestUtils.md5DigestAsHex((temp + md501).getBytes());
        return md502;
    }

    public static void main(String[] args) {
        String s = "password";
        System.out.println("原始串：" + s);
        System.out.println("MD5后：" + string2MD5(s));
        System.out.println("加密的：" + convertMD5(s));
        System.out.println("解密的：" + convertMD5(convertMD5(s)));

        System.out.println("spring==========================");
        System.out.println("MD5后：" + springMD5(s));
        System.out.println("解密：" + getMD5(springMD5(s)));
        System.out.println("解密：" + getMD5(getMD5(springMD5(s))));
    }
}





















